<?php
/**
 * +--------------------------------------------------------------
 * | eLuoPHP
 * +----------------------------------------------------------------
 * | Copyright (c) 2016-2019 http://qxwoo.cn All rights reserved.
 * +----------------------------------------------------------------
 * | y139w [y139w@163.com] Yier
 * +----------------------------------------------------------------
 * | 2019/12/14 22:17
 * +----------------------------------------------------------------
 * | Convert.php
 * +----------------------------------------------------------------
 */

namespace luo\traits;


trait Convert
{

    /**
     * array type to xml string type convert.
     * recursive processing array.
     * @param $array array this is array data
     * @return bool|string
     */
    public static function arrayToXml($array){

        // $array is not array type return false.
        if(!is_array( $array ) && count($array)){
            return false;
        }
        // return xml type string variable.
        $xml = "";
        // handle $data array variable split joint as string.
        // recursive processing of multidimensional array.
        foreach($array as $key => $val){
            if(is_array($val)){
                $xml .= '<' . $key . '>' . self::arrayToXml($val) . '</' . $key . '>';
            }else{
                $val = is_numeric($val) ? $val : '<![CDATA[' . $val . ']]>';
                $xml .= '<' . $key . '>' . $val . '</' . $key . '>';
            }
        }
        // return $xmlString variable.
        return $xml;

    }

    /**
     * xml string type to array type convert.
     * @param $data string xml string
     * @return bool|mixed
     */
    public static function xmlToArray($data){

        // if not string type return false.
        if(!is_string($data)){
            return false;
        }
        // string type xml to xml object type.
        $xmlObject = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
        // xml object type to json object type.
        $jsonObject = json_encode($xmlObject);
        // json object type to array type data.
        $array = json_decode($jsonObject, true);
        // json decode is not array return false.
        if(!is_array($array)){
            return false;
        }
        return $array;

    }

    /**
     * @param $array
     * @return object|void
     */
    public static function arrayToObject($array) {
        if (gettype($array) != 'array') {
            return;
        }
        foreach ($array as $key => $val) {
            if (gettype($val) == 'array' || gettype($val) == 'object') {
                $array[$key] = (object)self::arrayToObject($val);
            }
        }

        return (object)$array;
    }

}